package com.lmqb.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.lmqb.bean.JCheckArtificial;
import com.lmqb.bean.JCollection;
import com.lmqb.bean.LmLoan;
import com.lmqb.bean.LmRepay;
import com.lmqb.bean.LmUserInfo;
import com.lmqb.bean.SysMenu;
import com.lmqb.bean.SysRole;
import com.lmqb.bean.SysRolemenu;
import com.lmqb.bean.SysUser;
import com.lmqb.bean.SysWhiteList;
import com.lmqb.constant.MsgError;
import com.lmqb.constant.MsgSuccess;
import com.lmqb.dao.JCheckArtificialMapper;
import com.lmqb.dao.JCollectionMapper;
import com.lmqb.dao.LmLoanMapper;
import com.lmqb.dao.LmRepayMapper;
import com.lmqb.dao.LmUserInfoMapper;
import com.lmqb.dao.SysMenuMapper;
import com.lmqb.dao.SysRoleMapper;
import com.lmqb.dao.SysRolemenuMapper;
import com.lmqb.dao.SysUserMapper;
import com.lmqb.entry.RoleInfo;
import com.lmqb.page.EmailLogPager;
import com.lmqb.page.PagerModel;
import com.lmqb.responces.ResultData;
import com.lmqb.service.JiaoYanService;
import com.lmqb.util.StrUtil;

@Service("jiaoYanService")
public class JiaoYanServiceImpl implements JiaoYanService{

	@Autowired
	private SysUserMapper sysUserDao;
	
	@Autowired
	private SysMenuMapper sysMenuDao;
	
	@Autowired
	private SysRoleMapper sysRoleDao;
	
	@Autowired
	private JCheckArtificialMapper checkDao;
	
	@Autowired
	private SysRolemenuMapper sysRoleMenuDao;
	
	@Autowired
	private LmRepayMapper repayDao;
	
	@Autowired
	private JCollectionMapper cuishouDao;
	
	@Autowired
	private LmLoanMapper loanDao;
	
	@Autowired
	private LmUserInfoMapper lmUserInfoDao;
	
	//@Override
	public ResultData<SysUser> adminLogin(String username, String password) {
		ResultData<SysUser> resultData =new ResultData<SysUser>();
		if(StrUtil.isNull(username)){
			resultData.setError(MsgError.NullName);
			return resultData;
		}
		if(StrUtil.isNull(password)){
			resultData.setError(MsgError.NullPwd);
			return resultData;
		}
		
		resultData.setSuccess(null, MsgSuccess.ChengGong);
		return resultData;
	}

	//@Override
	public ResultData<SysUser> selectByUserName(String username) {
		ResultData<SysUser> resultData =new ResultData<SysUser>();
		SysUser sysUser=sysUserDao.selectByName(username);
		if(sysUser==null){
			resultData.setError(MsgError.NullUser);
			return resultData;
		}else{
			resultData.setSuccess(sysUser, MsgSuccess.ChengGong);
		}
		return resultData;
	}

	//@Override
	public ResultData<String> addMenu(SysMenu sysMenu) {
		ResultData<String> resultData=new ResultData<String>();
		if(StrUtil.isNull(sysMenu.getMenuCode())){
			resultData.setError(MsgError.NullMenuCode);
			return resultData;
		}
		if(StrUtil.isNull(sysMenu.getMenuName())){
			resultData.setError(MsgError.NullMenuName);
			return resultData;
		}
		if(sysMenu.getParentId()==null){
			resultData.setError(MsgError.NullMenuParentId);
			return resultData;
		}
		SysMenu sysMenu1=sysMenuDao.selectByMenuCode(sysMenu.getMenuCode());
		if(sysMenu1!=null){
			resultData.setError(MsgError.ExistedMenu);
			return resultData;
		}
		resultData.setSuccess(null, MsgSuccess.ChengGong);
		return resultData;
	}

	//@Override
	public ResultData<String> modifyMenu(SysMenu sysMenu) {
		ResultData<String> resultData=new ResultData<String>();
		if(sysMenu.getMenuId()==null){
			resultData.setError(MsgError.NullMenuId);
			return resultData;
		}
		if(StrUtil.isNull(sysMenu.getMenuCode())){
			resultData.setError(MsgError.NullMenuCode);
			return resultData;
		}
		if(StrUtil.isNull(sysMenu.getMenuName())){
			resultData.setError(MsgError.NullMenuName);
			return resultData;
		}
		if(sysMenu.getParentId()==null){
			resultData.setError(MsgError.NullMenuParentId);
			return resultData;
		}
		SysMenu sysMenu1=sysMenuDao.selectByMenuCode(sysMenu.getMenuCode());
		if(sysMenu1!=null&&sysMenu1.getMenuId()!=sysMenu.getMenuId()){
			resultData.setError(MsgError.ExistedMenu);
			return resultData;
		}
		resultData.setSuccess(null, MsgSuccess.ChengGong);
		return resultData;
	}

	/*
	 * 添加角色校验
	 * */
	public ResultData<String> addRole(RoleInfo roleInfo) {
		ResultData<String> resultData=new ResultData<String>();
		if(StrUtil.isNull(roleInfo.getRoleName())){
			resultData.setError(MsgError.NullRoleName);
			return resultData;
		}
		if(roleInfo.getMenuList()==null||roleInfo.getMenuList().size()==0){
			resultData.setError(MsgError.NullMenu);
			return resultData;
		}
		SysRole role=sysRoleDao.selectByName(roleInfo.getRoleName());
		if(role !=null){
			resultData.setError(MsgError.ExistedRole);
			return resultData;
		}
		Integer[] menuIds=new Integer[roleInfo.getMenuList().size()];
		roleInfo.getMenuList().toArray(menuIds);
		List<SysMenu> list=sysMenuDao.selectMenus(menuIds);
		if(list.size()<roleInfo.getMenuList().size()){
			resultData.setError(MsgError.InvalidMenuId);
			return resultData;
		}
		resultData.setSuccess(MsgSuccess.ChengGong, MsgSuccess.ChengGong);
		return resultData;
	}

	//@Override
	public ResultData<String> modifyRole(RoleInfo roleInfo) {
		ResultData<String> resultData=new ResultData<String>();
		if(roleInfo.getRoleId()==null){
			resultData.setError(MsgError.NullRoleId);
			return resultData;
		}
		if(StrUtil.isNull(roleInfo.getRoleName())){
			resultData.setError(MsgError.NullRoleName);
			return resultData;
		}
		if(roleInfo.getMenuList()==null||roleInfo.getMenuList().size()==0){
			resultData.setError(MsgError.NullMenu);
			return resultData;
		}
		SysRole role=sysRoleDao.selectByName(roleInfo.getRoleName());
		if(role !=null && role.getRoleId() !=roleInfo.getRoleId()){
			resultData.setError(MsgError.ExistedRole);
			return resultData;
		}
		Integer[] menuIds=new Integer[roleInfo.getMenuList().size()];
		roleInfo.getMenuList().toArray(menuIds);
		List<SysMenu> list=sysMenuDao.selectMenus(menuIds);
		if(list.size()<roleInfo.getMenuList().size()){
			resultData.setError(MsgError.InvalidMenuId);
			return resultData;
		}
		resultData.setSuccess(MsgSuccess.ChengGong, MsgSuccess.ChengGong);
		return resultData;
	}

	//@Override
	public ResultData<String> addSysUser(SysUser sysUser, String pwd1) {
		ResultData<String> resultData=new ResultData<String>();
		if(StrUtil.isNull(sysUser.getLoginName())){
			resultData.setError(MsgError.NullName);
			return resultData;
		}
		if(StrUtil.isMobile(sysUser.getMobile())){
			resultData.setError(MsgError.ErrorMobile);
			return resultData;
		}
		if(StrUtil.isNull(sysUser.getJob())){
			resultData.setError(MsgError.NullJob);
			return resultData;
		}
		if(StrUtil.isNull(sysUser.getRealName())){
			resultData.setError(MsgError.NullRealName);
			return resultData;
		}
		if(StrUtil.isNull(sysUser.getUserPwd())){
			resultData.setError(MsgError.NullPwd);
			return resultData;
		}
		if(!sysUser.getUserPwd().equals(pwd1)){
			resultData.setError(MsgError.PwdNotEqual);
			return resultData;
		}
		if(sysUser.getDeleteFlag()==null){
			resultData.setError(MsgError.NullDelFlag);
			return resultData;
		}
		if(sysUser.getRoleId()==null){
			resultData.setError(MsgError.NullRoleId);
			return resultData;
		}
		SysUser sysUser1=sysUserDao.selectByName(sysUser.getLoginName());
		if(sysUser1!=null){
			resultData.setError(MsgError.ExistedSysUser);
			return resultData;
		}
		SysUser sysUser2=sysUserDao.selectByMobile(sysUser.getMobile());
		if(sysUser2!=null){
			resultData.setError(MsgError.ExistedMobile);
			return resultData;
		}
		resultData.setSuccess(MsgSuccess.ChengGong, MsgSuccess.ChengGong);
		return resultData;
	}

	//@Override
	public ResultData<String> modifySysUser(SysUser sysUser, String pwd1) {
		ResultData<String> resultData=new ResultData<String>();
		if(sysUser.getUserId()==null){
			resultData.setError(MsgError.NullUserId);
			return resultData;
		}
		if(StrUtil.isMobile(sysUser.getMobile())){
			resultData.setError(MsgError.ErrorMobile);
			return resultData;
		}
		if(StrUtil.isNull(sysUser.getJob())){
			resultData.setError(MsgError.NullJob);
			return resultData;
		}
		if(StrUtil.isNull(sysUser.getLoginName())){
			resultData.setError(MsgError.NullName);
			return resultData;
		}
		if(StrUtil.isNull(sysUser.getRealName())){
			resultData.setError(MsgError.NullRealName);
			return resultData;
		}
		
		//密码不等于空的时候才判断
		if(!StrUtil.isNull(sysUser.getUserPwd())){
			if(!sysUser.getUserPwd().equals(pwd1)){
				resultData.setError(MsgError.PwdNotEqual);
				return resultData;
			}
		}
		if(sysUser.getDeleteFlag()==null){
			resultData.setError(MsgError.NullDelFlag);
			return resultData;
		}
		if(sysUser.getRoleId()==null){
			resultData.setError(MsgError.NullRoleId);
			return resultData;
		}
		if(sysUser.getUserStatus()==null){
			resultData.setError(MsgError.NullStatus);
			return resultData;
		}
		SysUser sysUser2=sysUserDao.selectByPrimaryKey(sysUser.getUserId());
		if(sysUser2==null){
			resultData.setError(MsgError.NullUser);
			return resultData;
		}
		//根据是否允许删除来判断是否允许把状态设为删除
		if(sysUser2.getDeleteFlag()==2&&sysUser.getUserStatus()==3){
			//原来的状态为不允许删除，并且修改后status为已删除
			resultData.setError(MsgError.NotAllowDel);
			return resultData;
		}
		SysUser sysUser3=sysUserDao.selectByMobile(sysUser.getMobile());
		System.out.println("管理员-->"+sysUser3);
		if(sysUser3!=null && sysUser3.getUserId() !=sysUser.getUserId()){
			resultData.setError(MsgError.ExistedMobile);
			return resultData;
		}
		SysUser sysUser1=sysUserDao.selectByName(sysUser.getLoginName());
		if(sysUser1!=null && sysUser1.getUserId() !=sysUser.getUserId()){
			resultData.setError(MsgError.ExistedSysUser);
			return resultData;
		}
		resultData.setSuccess(MsgSuccess.ChengGong, MsgSuccess.ChengGong);
		return resultData;
	}

	/**
	 * @show 传参之前的校验
	 * 
	 * @param PagerModel
	 * 
	 * @return PagerModel
	 * 
	 * */
	public <T> PagerModel<T> pagerModelFormat(PagerModel<T> pagerModel) {
		try{
            if(!StrUtil.isNull(pagerModel.getKey())){
				String key = new String(pagerModel.getKey().getBytes("ISO-8859-1"),"UTF-8");
				pagerModel.setKey(key);
			}
			if(!StrUtil.isNull(pagerModel.getTime1())){
				String time1 = new String(pagerModel.getTime1().getBytes("ISO-8859-1"),"UTF-8");
				pagerModel.setTime1(time1);
			}
			if(!StrUtil.isNull(pagerModel.getTime2())){
				String time2 = new String(pagerModel.getTime2().getBytes("ISO-8859-1"),"UTF-8");
				pagerModel.setTime2(time2);
			}
			pagerModel.setTime1Int(StrUtil.strToInt(pagerModel.getTime1()));
			pagerModel.setTime2Int(StrUtil.strToInt(pagerModel.getTime2()));
		}catch(Exception e){
			e.printStackTrace();
		}
		return pagerModel;
	}

	/*
	 * 修改密码
	 * */
	//@Override
	public ResultData<String> editPwd(String pwd, String pwd1, String pwd2,Integer userId) {
		ResultData<String> resultData=new ResultData<String>();
		if(StrUtil.isNull(pwd)){
			resultData.setError(MsgError.NullOldPwd);
			return resultData;
		}
		if(StrUtil.isNull(pwd1)){
			resultData.setError(MsgError.NullPwdNew);
			return resultData;
		}
		if(StrUtil.isNull(pwd2)){
			resultData.setError(MsgError.NullPwdEnter);
			return resultData;
		}
		if(!pwd1.equals(pwd2)){
			resultData.setError(MsgError.PwdNotEqual);
			return resultData;
		}
		SysUser admin=sysUserDao.selectByPrimaryKey(userId);
		if(!StrUtil.Get_MD5(pwd).equals(admin.getUserPwd())){
			resultData.setError(MsgError.ErrOldPwd);
			return resultData;
		}
		resultData.setStatus(0);
		return resultData;
	}

    /*
     * 添加审核记录的逻辑处理
     * */
	public ResultData<String> addCheck(JCheckArtificial check) {
		System.out.println("审核￥￥￥￥"+check);
		ResultData<String> result=new ResultData<String>();
		
		SysUser sysUser=sysUserDao.selectByPrimaryKey(check.getAdminId());
		List<SysRolemenu> list=sysRoleMenuDao.selectAllByRoleId(sysUser.getRoleId());
		Integer checkType=null;
		for(int i=0;i<list.size();i++){
			if(list.get(i).getMenuCode().equals("check_type_one")){
				checkType=1;
			}
			if(list.get(i).getMenuCode().equals("check_type_two")){
				checkType=2;
			}
			if(list.get(i).getMenuCode().equals("check_type_three")){
				checkType=3;
			}
		}
		if(check.getStatus()!=1){
			if(check.getErrMsg()==null){
				result.setError(MsgError.NullErrMsg);
				return result;
			}
		}else{
			if(StrUtil.isNull(check.getRemark())){
				result.setError(MsgError.NullRemark);
				return result;
			}
		}
		//初审
		if(check.getType()==(byte)1){
			if(checkType !=1){
				result.setError(MsgError.NotCheckPower);
				return result;
			}
			
			LmUserInfo lmUserInfo = lmUserInfoDao.selectByUserId(check.getUserId());
			if(lmUserInfo==null){
				result.setError(MsgError.NoUserAtLmUserInfo);
				return result;
			}if(lmUserInfo.getAuthStep() == 5 || lmUserInfo.getAuthStep() == 8){
				//不能重复初审
				JCheckArtificial select=new JCheckArtificial();
				select.setType((byte)1);
				//select.setCheckOneId(check.getCheckOneId());
				select.setUserId(check.getUserId());
				List<JCheckArtificial> checkTwo=checkDao.selectByRecord(select);//这个要改
				/*if(checkTwo !=null){
					result.setError(MsgError.NotCheckAgain);
					return result;
				}*/
				if(checkTwo.size()>0){
					for(int i=0;i<checkTwo.size();i++){
						if(checkTwo.get(checkTwo.size()-1).getStatus() != 3){
							result.setError(MsgError.NotCheckAgain);
							return result;
						}
						}
				}
			}
		}
		
		if(check.getType()==(byte)2){//复审，检查初审通过了没有，有没有复审过，管理员有没有这个权限
			if(checkType !=2){
				result.setError(MsgError.NotCheckPower);
				return result;
			}
//			JCheckArtificial select=new JCheckArtificial();
//			select.setType((byte)1);
//			select.setRecId(check.getCheckOneId());
			
			
			//之前处理逻辑 20.7.08.11
			/*JCheckArtificial checkOne=checkDao.selectByPrimaryKey(check.getCheckOneId());
			if(checkOne==null){
				result.setError(MsgError.NullCheckOne);
				return result;
			}
			if(checkOne.getStatus()!=(byte)1){
				result.setError(MsgError.NotPassOneCheck);
				return result;
			}*/
			LmUserInfo lmUserInfo = lmUserInfoDao.selectByUserId(check.getUserId());
			if(lmUserInfo==null){
				result.setError(MsgError.NoUserAtLmUserInfo);
				return result;
			}if(lmUserInfo.getAuthStep() == 6 || lmUserInfo.getAuthStep() == 9){
				//不能重复复审
				JCheckArtificial select=new JCheckArtificial();
				select.setType((byte)2);
				//select.setCheckOneId(check.getCheckOneId());
				select.setUserId(check.getUserId());
				List<JCheckArtificial> checkTwo=checkDao.selectByRecord(select);//这个要改
				/*if(checkTwo !=null){
					result.setError(MsgError.NotCheckAgain);
					return result;
				}*/
				if(checkTwo.size()>0){
					for(int i=0;i<checkTwo.size();i++){
						if(checkTwo.get(checkTwo.size()-1).getStatus() != 3){
							result.setError(MsgError.NotCheckAgain);
							return result;
						}
						}
				}
			}if(lmUserInfo.getAuthStep() != 5){
				result.setError(MsgError.NotPassOneCheck);
				return result;
			}
			
			
		}
		
		
		if(check.getType()==(byte)3){//终审，检查复审通过了没有，有没有终审过，管理员有没有这个权限，有没有额度。
			if(checkType !=3){
				result.setError(MsgError.NotCheckPower);
				return result;
			}
			//判断是否为复审通过
			LmUserInfo lmUserInfo = lmUserInfoDao.selectByUserId(check.getUserId());
			if(lmUserInfo==null){
				result.setError(MsgError.NoUserAtLmUserInfo);
				return result;
			}if(lmUserInfo.getAuthStep() == 7 || lmUserInfo.getAuthStep() == 10){
				//查看之前终审记录
				JCheckArtificial select=new JCheckArtificial();
				select.setType((byte)3);
				select.setUserId(check.getUserId());
				List<JCheckArtificial> checkThree=checkDao.selectByRecord(select);
				if(checkThree.size()>0){
					for(int i=0;i<checkThree.size();i++){
						if(checkThree.get(checkThree.size()-1).getStatus() != 3){
							result.setError(MsgError.NotCheckAgain);
							return result;
						}
						}
				}
			}if(lmUserInfo.getAuthStep() != 6){
				result.setError(MsgError.NotPassTwoCheck);
				return result;
			}
			
			//之前的逻辑2017.08.11 判断初审和复审记录
			/*JCheckArtificial checkOne=checkDao.selectByPrimaryKey(check.getCheckOneId());//根据初审id找到初审记录
			if(checkOne==null){
				result.setError(MsgError.NullCheckOne);
				return result;
			}
			if(checkOne.getStatus()!=(byte)1){
				result.setError(MsgError.NotPassOneCheck);
				return result;
			}*/
			/*JCheckArtificial select=new JCheckArtificial();
			select.setType((byte)2);
			select.setCheckOneId(check.getCheckOneId());
			System.out.println("审核bug"+check.getCheckOneId());
			List<JCheckArtificial> checkTwo=checkDao.selectByRecord(select);*/
			/*最开始的逻辑 if(checkTwo ==null){
				result.setError(MsgError.NullCheckTwo);
				return result;
			}
			if(checkTwo.getStatus()!=(byte)1){
				result.setError(MsgError.NotPassTwoCheck);
				return result;
			}
			select.setType((byte)3);
			JCheckArtificial checkThree=checkDao.selectByRecord(select);
			if(checkThree !=null){
				result.setError(MsgError.NotCheckAgain);
				return result;
			}*/
			/* 之后第二阶段逻辑if(checkTwo.size()<=0){
				result.setError(MsgError.NullCheckTwo);
				return result;
			}
			for(int i=0;i<checkTwo.size();i++){
			if(checkTwo.get(checkTwo.size()-1).getStatus()!=(byte)1){
				result.setError(MsgError.NotPassTwoCheck);
				return result;
			}
			}*/
			//终审不能重复操作
			/*select.setType((byte)3);
			JCheckArtificial checkThree=checkDao.selectByRecord(select);
			if(checkThree.getStatus()==1){
				result.setError(MsgError.NotCheckAgain);
				return result;
			}*/
			
		}
		
		
		result.setChengGong(MsgSuccess.ChengGong);
		return result;
	}

	/*
	 * 是否有催收权限
	 * */
	public Integer selectCuiShou(Integer userId) {
		SysUser sysUser=sysUserDao.selectByPrimaryKey(userId);
		List<SysRolemenu> list=sysRoleMenuDao.selectAllByRoleId(sysUser.getRoleId());
		Integer hasCuiShou=null;
		for(int i=0;i<list.size();i++){
			if(list.get(i).getMenuCode().equals("has_cuishou")){
				hasCuiShou=1;
			}
		}
		return hasCuiShou;
	}

	/*
	 * 最近一条还款记录
	 * */
	public LmRepay selectYuqi(Integer userId) {
		LmRepay repay=repayDao.selectMaxByUserId(userId);
		if(repay !=null&&repay.getOverdueDays()>0){
			return repay;
		}else{
			return null;
		}
	}

	//@Override
	public ResultData<String> addCuiShou(JCollection cuishou) {
		ResultData<String> result=new ResultData<String>();
		if(StrUtil.isNull(cuishou.getRepayNo())){
			result.setError(MsgError.NullRepayNo);
			return result;
		}
		if(StrUtil.isNull(cuishou.getRemark())){
			result.setError(MsgError.NullRemark);
			return result;
		}
		result.setStatus(0);
		return result;
	}

	/*
	 * 代理申请
	 * */
	public Integer CheckApply(Integer userId) {
		SysUser sysUser=sysUserDao.selectByPrimaryKey(userId);
		List<SysRolemenu> list=sysRoleMenuDao.selectAllByRoleId(sysUser.getRoleId());
		Integer checkApply=null;
		for(int i=0;i<list.size();i++){
			if(list.get(i).getMenuCode().equals("check_agent")){
				checkApply=1;
			}
		}
		return checkApply;
	}

	//添加白名单校验
	public ResultData<String> addWhiteList(SysWhiteList sysWhiteList) {
		ResultData<String> resultData=new ResultData<String>();
		if(sysWhiteList.getLoanMobile()==null||sysWhiteList.getLoanMobile()==""||sysWhiteList.getLoanMobile()=="null"){
			resultData.setError(MsgError.NullMboile);
			return resultData;
		}
		if(StrUtil.isMobile(sysWhiteList.getLoanMobile())){
			resultData.setError(MsgError.ErrorMobile);
			return resultData;
		}
		if(StrUtil.isNull(sysWhiteList.getUserName())){
			resultData.setError(MsgError.NullName);
			return resultData;
		}
		resultData.setChengGong(MsgSuccess.ChengGong);
		return resultData;
	}
}
